package com.example.rabbitmq.demo01.demo01;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.CancelCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Consumer {
    public static final String QUEUE_NAME="hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        //1、创建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();


        //2、设置工厂ip，即rabbitmq服务所在的地址
        factory.setHost("127.0.0.1");
        //3、设置rabbitmq的用户名
        factory.setUsername("guest");
        //4、设置rabbitmq的密码
        factory.setPassword("guest");


        //5、创建连接
        Connection connection = factory.newConnection();

        //6、获取连接中的信道
        Channel channel = connection.createChannel();


        //7、创建队列（使用默认交换机）
        //队列名称、队列里的消息是否持久化（默认存储在内存即不持久化，持久化则存于磁盘）、队列是否可供多个消费者消费、最后一个消费者端开链接后是否自动删除、其他参数
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);


        //8、接受消息
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.println(new String(message.getBody()));
        };
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("消费被中断");
        };


        //消费哪个队列、消费成功后是否自动应答、消费失败时的回调、消费者取消消费时回调
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);

        System.out.println("消息接收完毕");
    }
}
